<!--
  * 装车单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]" class="smart-margin-bottom10">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="司机" class="smart-margin-bottom0">
            <Select name="Driver" v-model:value="queryForm.driver_id" placeholder="司机" @inputEnter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="协送员" class="smart-margin-bottom0">
            <Select name="Driver" v-model:value="queryForm.escort_driver_id" placeholder="请选择" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="装车状态" class="smart-margin-bottom0">
            <EnumSelect enum-name="DELIVERY_STATUS_ENUM" v-model:value="queryForm.status" placeholder="装车状态" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQueryData">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
      </a-row>
      <a-row :gutter="[8, 10]" class="smart-margin-bottom10" v-show="expand">
        <a-col :span="4">
          <a-form-item label="装车单号" class="smart-margin-bottom0">
            <a-input v-model:value.trim="load_order_no" placeholder="装车单号" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="单据编号" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.no" placeholder="单据编号" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-card>

  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <!-- <a-button @click="addGoods()" type="primary" v-privilege="'delivery:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          手动调度
        </a-button>
        <a-button @click="goMap" type="primary" v-privilege="'delivery:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          地图调度
        </a-button> -->
        <!-- <a-button @click="showCustomPrint" type="primary" v-privilege="'goods:add'">
          <template #icon>
            <PrinterOutlined />
          </template>
          自定义配送单
        </a-button> -->
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'no'">
            <CopyText :text="text">
              <a @click="detail(record)">{{ text }}</a>
            </CopyText>
          </template>
          <template v-if="['total_volume', 'total_weight'].includes(column.dataIndex)">
            {{ text?.toFixed(2) }}
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="TagColor[text]">{{ getDescByValue('DELIVERY_STATUS_ENUM', Number(text)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c">详情</a-button>
              <a-button @click="print(record, '1')" type="link">配送销售单打印</a-button>
              <a-button @click="print(record, '2')" type="link">配送退货单打印</a-button>
              <!-- <template v-if="record.status === 1">
                <a-button @click="addGoods(record)" type="link" v-privilege="'delivery:edit'">编辑</a-button>
                <a-button @click="deleteData(record.id, record.no)" danger type="link" v-privilege="'delivery:del'">删除</a-button>
                <a-button @click="returnBack(record)" type="link" style="color: #e6a23c" v-privilege="'delivery:modify'"> 装车 </a-button>
              </template>
              <template v-if="record.status === 2 && record.sign_status == 0">
                <a-button @click="cancelOrder(record)" danger type="link" v-privilege="'delivery:cancel'">驳回</a-button>
              </template>
              <a-button @click="print(record)" type="link">配送单打印</a-button> -->
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>

    <DeliveryFormModal ref="formModal" @reload-list="queryData" />
    <!---------- 详情 begin ----------->
    <DeliveryDetailsModal ref="detailRef" @reload-list="queryData" />
    <!---------- 详情 end ----------->
    <DeliveryPrintModal ref="printRef" />
  </a-card>
</template>
<script setup lang="ts">
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import DeliveryPrintModal from './components/delivery-print-modal.vue'
import DeliveryDetailsModal from './components/delivery-details-modal.vue'
import DeliveryFormModal from './components/delivery-form-modal.vue'
import { message, Modal } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { taskApi } from '@/api/business/logistics/delivery-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import { errorSentry } from '@/lib/error-sentry'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import Select from '@/components/business/select/index.vue'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import _ from 'lodash'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
const appConfigStore = useAppConfigStore()
const { getDescByValue } = useEnums()
const loadingStore = useLoadingStore()
enum TagColor {
  'error' = 1,
  'success'
}
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '装车单号',
    dataIndex: 'no',
    width: appConfigStore.$state.compactFlag ? 150 : 180
  },
  {
    title: '单据数量',
    dataIndex: 'order_num'
  },
  {
    title: '配送金额',
    dataIndex: 'delivery_amount'
  },
  {
    title: '配送数量',
    dataIndex: 'delivery_num'
  },
  {
    title: '司机',
    dataIndex: ['driver', 'name']
  },
  {
    title: '协送员',
    dataIndex: ['escortDriver', 'name']
  },
  {
    title: '单据时间',
    dataIndex: 'create_time'
  },
  {
    title: '装车状态',
    dataIndex: 'status'
  },
  {
    title: '体积(m³)',
    dataIndex: 'total_volume',
    width: 80
  },
  {
    title: '重量(kg)',
    dataIndex: 'total_weight',
    width: 80
  },
  {
    title: '制单员',
    dataIndex: ['creator', 'username']
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 100 : 140
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const load_order_no = ref('')
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData } = useQuery({
  fetchDataApi: async (params) => {
    const { page, limit, op } = params
    const { ...filter } = params.filter
    const data = {
      page,
      limit,
      op,
      filter,
      load_order_no: load_order_no.value
    }
    const res = await taskApi.queryTaskList(data)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await taskApi.delLoad({ id })
    return !!res
  },
  queryFormFilter: {
    no: '',
    create_time: DEFAULT_TIME_RANGE.value,
    driver_id: null,
    status: null
  },
  queryFormOp: {
    no: QUERY_FORM_OP['模糊查询'],
    create_time: QUERY_FORM_OP['范围查询'],
    driver_id: QUERY_FORM_OP['全等查询'],
    status: QUERY_FORM_OP['全等查询']
  }
})

onActivated(queryData)
const resetQueryData = () => {
  load_order_no.value = ''
  resetQuery()
}
// ---------------------------- 添加 ----------------------------
const formModal = ref()

function addGoods(goodsData) {
  formModal.value.showDrawer(goodsData)
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}

// ---------------------------- 打印 ----------------------------
const printRef = ref()

const print = (goodsData, val) => {
  printRef.value.showDrawer(goodsData, val)
}
// ---------------------------- 确定装车 ----------------------------

function returnBack(goodsData) {
  Modal.confirm({
    title: '提示',
    content: '确定装车【' + goodsData.no + '】吗?',
    okText: '确定装车',
    okType: 'danger',
    onOk() {
      singleDelete(goodsData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleDelete(goodsData) {
  try {
    loadingStore.show()
    const res = await taskApi.modifyLoad({ id: goodsData.id, field: 'status', value: 2 })
    message.success(res.msg)
    router.push('/logistics/list')
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

// ---------------------------- 取消装车 ----------------------------

function cancelOrder(goodsData) {
  Modal.confirm({
    title: '提示',
    content: '确定驳回吗?',
    okText: '确定',
    onOk() {
      cancelDelete(goodsData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function cancelDelete(goodsData) {
  try {
    loadingStore.show()
    const res = await taskApi.cancelLoading({ id: goodsData.id })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

// ---------------------------- 批量 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys
}

// 跳转地图调度
const router = useRouter()
function goMap() {
  router.push({ path: '/map' })
}

// 自定义配送单打印
const customPrintRef = ref()
function showCustomPrint() {
  customPrintRef.value?.showDrawer()
}
</script>
